<template>
  <el-dialog v-model="dialogFormVisible" top="5vh" :title="titleComputed" width="500px" @close="handleDialogClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="155px">
      <el-form-item label="Call车名称 :" prop="callName">
        <el-input
          v-if="props.isEdit"
          v-model="form.callName"
          :disabled="!!form.id && ['3'].includes(props.callType.toString())"
          autocomplete="off"
          placeholder="请输入Call车名称"
        />
        <span v-else>{{ form.callName }}</span>
      </el-form-item>
      <el-form-item label="VIN清单 :" prop="fileId">
        <CommonUpload
          v-if="props.isEdit"
          accept=".xlsx,.xls"
          class="upload-demo"
          show-file-list
          icon
          :action="uploadCarFileApi()"
          :file-list="fileList"
          :download-url="downloadCallTemplateApi"
          @handleSuccessData="handleSuccessData"
          @handlePreview="handlePreview"
        />
        <ElButton v-else link type="primary" @click="handleDownload">{{ form.fileName }}</ElButton>
      </el-form-item>
      <el-form-item label="Call车数量 :" prop="callNum">
        <el-input
          v-if="props.isEdit"
          v-model="form.callNum"
          disabled
          autocomplete="off"
          placeholder="请输入Call车数量"
        />
        <span v-else>{{ form.callNum }}</span>
      </el-form-item>
      <el-form-item v-if="props.callType == '1'" label="融资账户 :" prop="accountType">
        <el-select v-if="props.isEdit" v-model="form.accountType" placeholder="请选择融资账户">
          <el-option v-for="p in accountTypeOptions" :key="p.dicCode" :label="p.dicName" :value="p.dicCode" />
        </el-select>
        <span v-else>{{ form.accountType }}</span>
      </el-form-item>
      <el-form-item v-if="props.callType == '1'" label="Call车保证金(合计) :" prop="bond">
        <el-input
          v-if="props.isEdit"
          v-model="form.bond"
          disabled
          autocomplete="off"
          placeholder="请输入Call保证金(合计)"
        />
        <span v-else>{{ form.bond }}</span>
      </el-form-item>
      <el-form-item v-if="['2', '3'].includes(props.callType.toString())" label="Call车费用(合计) :" prop="rebate">
        <el-input
          v-if="props.isEdit"
          v-model="form.rebate"
          disabled
          autocomplete="off"
          placeholder="请输入Call车费用(合计)"
        />
        <span v-else>{{ form.rebate }}</span>
      </el-form-item>
      <el-form-item label="Call车日期 :" prop="callTime">
        <el-date-picker
          v-if="props.isEdit"
          v-model="form.callTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="datetime"
          placeholder="请选择Call车日期"
        />
        <span v-else>{{ form.callTime }}</span>
      </el-form-item>
      <el-form-item label="说明 :" prop="remark">
        <el-input
          v-if="props.isEdit"
          v-model="form.remark"
          autocomplete="off"
          :rows="2"
          type="textarea"
          placeholder="请输入说明"
        />
        <span v-else>{{ form.remark }}</span>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { reactive, ref, defineExpose, defineProps, defineEmits, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import CommonUpload from '@/components/CommonUpload/index.vue';
import useDialogForm from '@/hooks/useDialogForm';
import { validateMoney, validateInteger } from '@/utils/validate';
import useDictList from '@/hooks/useDictList';
import { exportFileUtil } from '@/utils/';
import {
  createCallApi,
  modifyCallApi,
  uploadCarFileApi,
  exportOrderCallFileApi,
  downloadCallTemplateApi,
} from '@/api/account_manage';

const titleComputed = computed(() => {
  if (form.id) {
    if (Number(props.callType) === 2) return '修改返利Call车';
    if (Number(props.callType) === 3) return '修改现金Call车';
    return '修改库融Call车';
  }
  if (Number(props.callType) === 2) return '新增返利Call车';
  if (Number(props.callType) === 3) return '新增现金Call车';
  return '新增库融Call车';
});

const accountTypeOptions = useDictList('FINANCE_ACCOUNT');

const { dialogFormVisible, formRef, validateForm } = useDialogForm();

type Form = {
  callType: string | number;
  callName: string | number;
  fileId: string | number | any;
  callNum: string | number;
  accountType: string | number;
  bond: string | number;
  rebate: string | number;
  callTime: string | number;
  remark: string | number;
  fileName: string | any;
  id?: string | number;
};
const form = reactive<Form>({
  callType: '',
  callName: '',
  fileId: '',
  callNum: '',
  accountType: '',
  bond: '0.00',
  rebate: '0.00',
  callTime: '',
  remark: '',
  fileName: '',
});

const fileList = ref<Array<any>>([]);

const handleOpen = (row: any) => {
  if (row) {
    const { callName, fileId, callNum, accountType, bond, rebate, callTime, remark, id, fileName } = row;
    form.callName = callName;
    form.fileId = fileId;
    form.callTime = callTime;
    form.callNum = callNum;
    form.accountType = accountType;
    form.bond = bond;
    form.rebate = rebate;
    form.remark = remark;
    form.fileName = fileName;
    form.id = id;
    fileList.value = [{ name: fileName, id, url: '', uid: id }];
  }
  formRef.value?.clearValidate();
  dialogFormVisible.value = true;
};

watch(
  () => props.callType,
  () => {
    form.callType = props.callType;
  }
);

const handleDialogClose = () => {
  form.callName = '';
  form.fileId = '';
  form.callTime = '';
  form.callNum = '';
  form.accountType = '';
  form.bond = '0.00';
  form.rebate = '0.00';
  form.remark = '';
  form.fileName = '';
  form.id = undefined;
  fileList.value = [];
};

const handleSubmit = async () => {
  try {
    await validateForm();
    const res = form.id ? await modifyCallApi(form) : await createCallApi(form);
    const { code, msg } = res;
    if (code === 10000) {
      ElMessage.success(msg);
      emit('handleRefresh');
      dialogFormVisible.value = false;
    } else {
      ElMessage.error(msg);
    }
  } catch (error) {
    console.error(error);
  }
};

const handleDownload = async (id: any = form.id) => {
  try {
    const res = await exportOrderCallFileApi(id);
    if (res) {
      exportFileUtil(res);
    }
  } catch (e) {
    console.error(e);
  }
};

const handlePreview = (file: any) => {
  if (file.id) {
    handleDownload(file.id);
  } else {
    ElMessage.warning('没有报错无法下载');
  }
};

const handleSuccessData = (res: any) => {
  const { code, msg, data } = res.response;
  if (code === 10000) {
    console.log(data, 'ssss');
    const { bondSum, carNum, fileId, callPriceSum } = data;
    form.fileId = fileId;
    form.callNum = carNum;
    form.bond = bondSum;
    form.rebate = callPriceSum;
    fileList.value = [{ name: res.uploadFile.name, id: undefined, url: '', uid: res.uploadFile.uid }];
  } else {
    ElMessage.error(msg);
    fileList.value = [];
  }
};

const rules = reactive<any>({
  callName: [{ required: true, message: '请输入Call车名称', trigger: 'change' }],
  fileId: [{ required: true, message: '请上传vin清单', trigger: 'change' }],
  callNum: [
    { required: true, message: '请输入Call车数量', trigger: 'change' },
    { validator: validateInteger, trigger: 'change' },
  ],
  accountType: [{ required: true, message: '请选择融资账户', trigger: 'change' }],
  bond: [
    { required: true, message: '请输入Call保证金(合计)', trigger: 'change' },
    { validator: validateMoney, trigger: 'change' },
  ],
  rebate: [
    { required: true, message: '请输入Call车费用(合计)', trigger: 'change' },
    { validator: validateMoney, trigger: 'change' },
  ],
  callTime: [{ required: true, message: '请选择Call车时间', trigger: 'change' }],
  remark: [{ min: 0, max: 200, message: '长度为0到200个字符', trigger: 'change' }],
});

const props = defineProps<{ callType: string | number; isEdit: boolean }>();
const emit = defineEmits(['handleRefresh']);
defineExpose({ handleOpen });
</script>

<style lang="scss" scoped>
.upload-demo {
  width: 100%;
  // height: 32px;
}
</style>
